<?php

namespace services\models;

use Yii;
use yii\base\Exception;

class Payment extends \services\models\OrderInfo {

	/**
	 * 验证数据
	 * @method validateData
	 * @param {string} $hash 加密hash串
	 * @param {string} $key 密钥
	 * @return {boolean}
	 * @example $this->validateData($hash, $key);
	 */
	public function validateData($hash, $key) {
		return Yii::$app->security->compareString($hash, $this->generateDataHash($key));
	}

	/**
	 * 生成加密hash串
	 * @method generateDataHash
	 * @param {string} $key 密钥
	 * @return {string}
	 * @example $this->generateDataHash($key);
	 */
	public function generateDataHash($key) {
		return hash_hmac('sha256', $this->getDataString(), $key, false);
	}

	/**
	 * 获取数据加密串
	 * @method getDataString
	 * @return {string}
	 */
	private function getDataString() {
		return $this->order_info_id .$this->bestry_uid . $this->order_amount;
	}
	
	
	/**
	 * 按id查找记录
	 * @method findById
	 * @param {number} $id 记录id
	 * @param {boolean} $toArray 数组格式化
	 * @return {object}
	 * @example static::findById($id, $toArray);
	 */
	public static function getOrderInfoByPramas($params, $toArray = false) {
	    $data = static::findOne($params);
	    if(!$data) {
	        throw new Exception( 'Data query failed');
	    }
	    if($toArray) {
	        $data = $data->toArray();
	    }
	
	    return $data;
	}
	
	/**
	 * 获取hash加密串
	 * @method getPaymentHash
	 * @param {number} [$id=null] 支付单id
	 * @return {string}
	 */
	public static  function getPaymentHash($id) {


	    $data = self::getOrderInfoByPramas(['order_info_id'=>$id]);
	    if(!$data) {
	        return null;
	    }
        return hash_hmac('sha256', $data->order_info_id . $data->bestry_uid . $data->order_amount, Yii::$app->params['hashkey'], false);
	     
	}
	

}
